<?php
@session_start();


class nfwkForms extends nfwk {
    
    
    public function genFormAttributes($givenAttributes=null, $scope=null) {
        
        // Variabile che conterrà il contenuto degli attributi da associare al Form
        $ReturnAttributes = null;
        
        if (!empty($givenAttributes)) {
            
            switch (strtolower(trim($scope))) {
                
                case "form":
                    $attrib = explode(NFWK_SEPARATOR, trim($givenAttributes));
                    foreach($attrib as $attribElement) {
                        foreach($this->_frmAttributesArray as $defElement) {
                            if (preg_match("/".$defElement."=/i", $attribElement)) {
                                $ReturnAttributes .= trim(str_replace($defElement."=", $defElement."=\"", $attribElement))."\" ";
                            }

                        }
                    }
                    break;
                    
                case "field":
                    $attrib = explode(NFWK_SEPARATOR, trim($givenAttributes));
                    foreach($attrib as $attribElement) {
                        foreach($this->_fldAttributesArray as $defElement) {
                            if (preg_match("/".$defElement."/i", $attribElement)) {
                                if ($attribElement == "disabled") {
                                    $ReturnAttributes .= "disabled ";
                                } else if ($attribElement == "checked") {
                                    $ReturnAttributes .= "checked ";
                                } else {
                                    $ReturnAttributes .= trim(str_replace($defElement."=", $defElement."=\"", $attribElement))."\" ";
                                }
                            } 

                        }
                    }
                    break;
                    
                case defalut:
                    break;
            }

        }

        return trim($ReturnAttributes);
        
    }
    
    
    //------------------------------------------------------------------------//

    public function hideFieldsinQuery($tohide=null) {

        $this->_HiddenFieldsinQuery = null;
        $FieldsToHide = null;
        
        if (!empty($tohide)) {
            $this->_frmHiddenElements = explode(NFWK_SEPARATOR, trim($tohide));
        }
        
        foreach (explode(NFWK_SEPARATOR, trim($tohide)) as $element) {
            $FieldsToHide .= "'".trim($element)."'  ";
        }
        
        $FieldsToHide = str_replace("  ", ", ", trim($FieldsToHide));
        
        $this->_HiddenFieldsinQuery = " AND name NOT IN ( ".$FieldsToHide." )";

        return 0;
        
    }
    
    
    //------------------------------------------------------------------------//

    
    public function genFormField($type=null, $name=null, $value=null, $attrib=null, $label=null, $labelattribs=null, $checked=null) {

        $SystemMessages = new nfwkLocales();
        $ElementAttribs = new nfwkForms();
        $LabelAttribs   = new nfwkForms();
        
        
        $ReturnElement = null;
        
        try {
            if (empty($type)) { throw new nfwkException($SystemMessages->ReturnError("40000")); }
            if (empty($name)) { throw new nfwkException($SystemMessages->ReturnError("40000")); }
            
            $type = trim(strtolower($type));

            switch($type) {
                case ($type == "text" || $type == "password"):
                    $FieldValue = " value=\"".trim($value)."\"";
                    break;

                case ($type == "textarea" || $type == "select" || $type == "checkbox" || $type == "radio"):
                    $FieldValue = "";
                    break;

                default:
                    $FieldValue = "";
                    break;

            }
            
            
            /* Se nella chiamata alla funzione viene specificato che deve essere
             * generata anche la label per il campo, in questo ciclo viene 
             * generata secondo le specifiche indicate. Altrimenti non viene
             * inserita alcuna label per il campo.
             */
            if (!empty($label)) {
                if (!empty($labelattribs)) {
                    $FieldLabel = "<label for=\"".$name."\" ".$LabelAttribs->genFormAttributes($labelattribs, "field").">".$label."</label>\n";
                } else {
                    $FieldLabel = "<label for=\"".$name."\" ".$LabelAttribs->genFormAttributes($labelattribs, "field").">".$label."</label>\n";
                }
            } else {
                $FieldLabel = "\n";
            }

            
            /* Ciclo la generazione dei campi in base al tipo specificato nella
             * chiamata alla funzione.
             */
            switch (strtolower(trim($type))) {
                
                case "text":
                    $ReturnElement = $FieldLabel."<input type=\"text\" name=\"".trim($name)."\"".$FieldValue." ".$ElementAttribs->genFormAttributes($attrib, "field")." />\n";
                    break;

                case "password":
                    $ReturnElement = $FieldLabel."<input type=\"password\" name=\"".trim($name)."\"".$FieldValue." ".$ElementAttribs->genFormAttributes($attrib, "field")." />\n";
                    break;
                
                case "textarea":
                    $ReturnElement = $FieldLabel."<textarea name=\"".trim($name)."\" ".$ElementAttribs->genFormAttributes($attrib, "field").">".$value."</textarea>\n";
                    break;

                case "select":
                    $ReturnElement = $FieldLabel."<select name=\"".trim($name)."\" ".$ElementAttribs->genFormAttributes($attrib, "field").">".$value."</select>\n";
                    break;
                
                case "radio":
                    $ReturnElement = $FieldLabel."<br>";
                    
                    foreach($value as $Values) {
                        $check = " ";

                        if (preg_match("/".$Values[0]."|".$Values[1]."/i", strtolower($checked))) {
                            $check = " checked ";
                        } else {
                            $check = " ";
                        }
                        
                        $ReturnElement .= "<input type=\"radio\" name=\"".trim($name)."\" value=\"".$Values[0]."\"".$check."/>".$Values[1]."\n<br/>";
                    }
                    break;
                    
                case "checkbox":
                    $ReturnElement = $FieldLabel."<br>";;

                    foreach($value as $Values) {
                        
                        $check = " ";

                        if (preg_match("/".$Values[0]."|".$Values[1]."/i", strtolower($checked))) {
                            $check = " checked ";
                        } else {
                            $check = " ";
                        }
                        
                        $ReturnElement .= "<input type=\"checkbox\" name=\"".trim($name)."\" value=\"".$Values[0]."\"".$check."/>".$Values[1]."\n<br/>";
                    }
                    break;
                
                default:
                    $ReturnElement = $FieldLabel."<input type=\"text\" name=\"".trim($name)."\"".$FieldValue.$ElementAttribs->genElementAttributes($attrib).">\n";
                    break;
                
            }
            

            
            
        } catch(nfwkException $e) {
            echo $e->getMessage();
        }
        
        
        return $ReturnElement;
        
    }
    
    
    
    
    //------------------------------------------------------------------------//

    
    public function genOptionFromPair($value=null, $label=null, $default=null, $attrib=null) {
        
        $SystemMessages = new nfwkLocales();
        $ElementAttribs = new nfwkForms();

        try {
            if (empty($value)) { throw new nfwkException($SystemMessages->ReturnError("40000")); }
            if (empty($label)) { throw new nfwkException($SystemMessages->ReturnError("40000")); }

            if (strtolower(trim($default)) == strtolower(trim($value)) || strtolower(trim($default)) == strtolower(trim($label))) {
                $default = "selected";
            } 

            $StringReturn = "<option ".trim($default)." ".$ElementAttribs->genFormAttributes($attrib, "field")." value=\"".trim($value)."\">".trim($label)."</option>\n";

        } catch(nfwkException $e) {
            echo $e->getMessage();
        }

        // Stampo sulla pagina la liste delle <OPTION>
        echo $StringReturn;

    }

    
    //------------------------------------------------------------------------//

    
    public function genOptionFromArray($ArrayValue, $default=null, $attrib=null, $return="echo") {
        
        $SystemMessages = new nfwkLocales();
        $ElementAttribs = new nfwkForms();
        
        $StringReturn = null;

        try {
            if (!array($ArrayValue)) { throw new nfwkException($SystemMessages->ReturnError("40000")); }

            foreach ($ArrayValue as $Val) {
                

                
                if (strtolower(trim($default)) == strtolower(trim($Val[0])) || strtolower(trim($default)) == strtolower(trim($Val[1]))) {
                    $defaultValue = " selected";
                } else {
                    $defaultValue = null;
                }
            
                $StringReturn .= "\n<option".$defaultValue." ".$ElementAttribs->genFormAttributes($attrib, "field")." value=\"".trim($Val[0])."\">".trim($Val[1])."</option>";
            }

        } catch(nfwkException $e) {
            echo $e->getMessage();
        }

        // Stampo sulla pagina la liste delle <OPTION>
        if ($return == "echo") {
            echo $StringReturn; 
        } else {
            return $StringReturn;
        }

    }
    
    
    
    public function genForm($name=null, $id="slug", $enc="span") {
        
        $ReturnForm = null;
        
        switch(trim(strtolower($id))) {
            
            case "slug":
               $QueryToDo = "SELECT * FROM core_objects_base WHERE slug = '".trim(strtolower(str_replace(" ", "-", $name)))."'";
                break;
            case "name":
                $QueryToDo = "SELECT * FROM core_objects_base WHERE name = '".trim($name)."'";
                break;
            case "id":
                $QueryToDo = "SELECT * FROM core_objects_base WHERE id = ".$name;
                break;
            default:
               $QueryToDo = "SELECT * FROM core_objects_base WHERE slug = '".trim(strtolower(str_replace(" ", "-", $name)))."'";
               break; 
        }

        
        $Form = new nfwkDB();
        $objForm = $Form->exeGetRow($QueryToDo);

        /* Con questa query recupero l'elenco dei campi e tutte le informazioni
         * necessarie per generare il form. Se prima della chiamata della
         * funzione, viene specificato quali campi omettere dalla generazione,
         * questi non saranno visualizzati e le informazioni non saranno recuperate
         * dalla tabella core_objects_elements del database.
         */
        $QueryFormFields = "SELECT * FROM core_objects_elements WHERE fk_object_base_id = ".$objForm['id']." AND active = 1 ".$this->_HiddenFieldsinQuery;

        
        $ReturnForm .= "\n";
        $ReturnForm .= "<form name=\"".$objForm['name']."\" ".nfwkForms::genFormAttributes($objForm['attributes'], "form").">\n";

        /* Genero i campi del form recuperando tutte le informazioni necessarie
         * dalla tabella core_objects_elements del database.
         */
        foreach($Form->exeQuery($QueryFormFields) as $row) {
            $ReturnForm .= "<".$enc.">".
                    nfwkForms::genFormField("text",         // Tipo di campo
                            $row['name'],                   // Nome del campo
                            $row['default_value'],          // Valore di default
                            $row['field_attributes']." ".   // Attributi del campo (da DB)
                            $row['event_attributes'],       // Attributi evento (da DB)
                            $row['label_name'],             // label del campo
                            $row['label_attributes']        // attributi della label (da DB)
                    )."</".$enc.">\n";
        }
        
        $ReturnForm .= "</form>";
        $ReturnForm .= "\n";
        
        
        //print_r($this->_frmBaseArray);
        
        return $ReturnForm;
        
        
        
    }

    
    

    
    
}








    
    //------------------------------------------------------------------------//

    /*
    public function genElementAttributes($givenAttributes=null) {

        if (!empty($givenAttributes)) {
            
            $attributes = explode(NFWK_SEPARATOR, trim($givenAttributes));
            
            foreach ($attributes as $element) {
                
                if (preg_match("/id=/i", $element))       $this->_fieldOpt['opt']['id'] = trim(str_replace("id=", "id=\"", $element))."\"";
                if (preg_match("/class=/i", $element))    $this->_fieldOpt['opt']['class'] = trim(str_replace("class=", "class=\"", $element))."\"";
                if (preg_match("/style=/i", $element))    $this->_fieldOpt['opt']['style'] = trim(str_replace("style=", "style=\"", $element))."\"";
                if (preg_match("/title=/i", $element))    $this->_fieldOpt['opt']['title'] = trim(str_replace("title=", "title=\"", $element))."\"";
                if (preg_match("/xmllnag=/i", $element))  $this->_fieldOpt['opt']['xmllnag'] = trim(str_replace("xml:lang=", "xml:lang=\"", $element))."\"";
                if (preg_match("/disabled=/i", $element)) $this->_fieldOpt['opt']['disabled'] = "disabled";
                if (preg_match("/readonly/i", $element))  $this->_fieldOpt['opt']['disabled'] = "readonly";

            }
            
            
            foreach ($this->_fieldOpt['opt'] as $elementOpt) {
                $this->_SReturn .= " ".$elementOpt;
            }
        }
        
        return " ".trim($this->_SReturn);
        
            
    }
    
     */
    
    
    //------------------------------------------------------------------------//
    


?>
